package com.yuntian.filter;

import com.alibaba.fastjson.JSONObject;
import com.yuntian.pojo.Result;
import com.yuntian.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

//@Component
//@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFIlter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //【HttpServletRequest】是【ServletRequest】的父类，【HttpServletResponse】是【ServletResponse】的父类
        //为什么强转request和response的类型？因为ServletRequest没有【.getRequestURI()】获取【请求url】的功能
        //ServletResponse也没有【.getWriter().write("...")】可以直接把内容写进【响应头】的方法

        //1.获取请求url
        String url = httpServletRequest.getRequestURI().toString();
        log.info("url",url);
        //2.判断请求ur1中是否包含login，如果包含，说明是登录操作，放行。
        if (url.contains("login")){
            log.info("登录操作，放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //3.获取请求头中的令牌（token）
        String jwt = ((HttpServletRequest) servletRequest).getHeader("token");
        //4.判断令牌是否存在，如果不存在，返回错误结果（未登录）
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头为空，返回未登录信息");
            Result error = Result.error("NOT_LOGIN");
            String jsonError = JSONObject.toJSONString(error);
            httpServletResponse.getWriter().write(jsonError);
            return;
        }
        //5.解析token，如果解析失败，返回错误结果（未登录）。
        try {
            JwtUtils.parseJWT(jwt);

        } catch (Exception e) {//jwt解析失败
            e.printStackTrace();
            log.info("解析令牌失败");
            Result error = Result.error("NOT_LOGIN");
            String jsonError = JSONObject.toJSONString(error);
            httpServletResponse.getWriter().write(jsonError);
            return;
        }

        //6.放行。
        log.info("令牌执行成功");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
